package com.lonely.controller;

import com.lonely.entity.bash.Result;
import com.lonely.entity.po.PaymentPo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @date: 2021-11-02 14:01
 * @author: ztkj-hzb
 * @description: 订单模块
 **/
@RestController
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 通过该对象获取注册中心的实例数据
     */
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/consumer/get/{id}")
    public Result<PaymentPo> getById(@PathVariable("id") Long id) {
        return this.restTemplate.getForObject("http://localhost:8001/payment/get/" + id, Result.class);
    }


    @PostMapping("/consumer/insert")
    public Result<Boolean> insert(@RequestBody PaymentPo paymentPo) {
        return this.restTemplate.postForObject("http://localhost:8001/payment/insert", paymentPo, Result.class);
    }


    /**
     * 通过eureka注册中心来获取指定服务名对应的url请求地址(单机版本)
     *
     * @param id
     * @return
     */
    @GetMapping("/consumer/get/eureka/simple/{id}")
    public Result<PaymentPo> getById2(@PathVariable("id") Long id) {

        //通过服务名获取对应的实例集合
        List<ServiceInstance> instances = this.discoveryClient.getInstances("cloud-payment-service");

        //因为是单机版本，所以只需要获取第一条记录
        ServiceInstance serviceInstance = instances.get(0);

        String url = String.format("%s/payment/get/%s", serviceInstance.getUri().toString(), id);

        return this.restTemplate.getForObject(url, Result.class);
    }


}
